from django.contrib.auth import login,authenticate,logout
from django.shortcuts import render
from django.http import JsonResponse,HttpResponse
from django_redis import get_redis_connection
from meiduo_mall.utils.views import LoginRequiredJSONMixin
from .models import User
from django.views import View
# Create your views here.
import json
import re

class UsernameCountView(View):
    def get(self,request,username):
        print(username)
        count = User.objects.filter(username=username).count()
        result = {
            'code':0,
            'errmsg':'OK',
            'count':count
        }
        return JsonResponse(result)

class MobileCountView(View):
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()
        result = {
            'code':0,
            'errmsg':'OK',
            'count':count
        }
        return JsonResponse(result)

class RegisterView(View):
    def post(self,request):
        json_b = request.body
        print(json_b)
        json_str = json_b.decode()
        json_dict = json.loads(json_str)
        username = json_dict['username']
        password = json_dict['password']
        password2 = json_dict['password2']
        mobile = json_dict['mobile']
        sms_code = json_dict['sms_code']
        allow = json_dict['allow']
        if not all([username,password,password2,mobile,sms_code,allow]):
            return JsonResponse({'code':400,'errmsg':'缺少必传参数'})
        if not re.match(r'^[0-9A-Za-z-_]{5,20}$',username):
            return JsonResponse({'code':400,'errmsg':'用户名格式错误'})
        if not re.match(r'^[a-zA-Z0-9]{8,20}$',password):
            return JsonResponse({'code':400,'errmsg':'密码格式错误'})
        if password != password2:
            return JsonResponse({'code':400,'errmsg':'密码两次输入不正确'})
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return JsonResponse({'code':400,'errmsg':'手机号格式错误'})
        if allow != True:
            return JsonResponse({'code':400,'errmsg':'allow格式有误'})

        conn = get_redis_connection('verify_code')
        user_sms = conn.get('sms_%s'%mobile)
        if not user_sms:
            return JsonResponse({'code':400,'errmsg':'验证码过期'})
        user_sms = user_sms.decode()
        if user_sms != sms_code:
            return JsonResponse({'code':400,'errmsg':'请输入正确的手机验证码'})

        try:
            user = User.objects.create_user(username=username,password=password,mobile=mobile)

        except Exception as e:
            return JsonResponse({'code':400,'errmsg':'注册失败！'})
        login(request,user)
        response =  JsonResponse({'code':0,'errmsg':'注册成功！'})
        response.set_cookie('username',user.username,max_age=3600*24*14)
        return response


class LoginView(View):
    def post(self,request):
        json_data = request.body
        json_data = json_data.decode()
        json_str = json.loads(json_data)
        username = json_str.get('username')
        password = json_str.get('password')
        remembered = json_str.get('remembered')

        print(username,password,remembered)
        if not all([username,password]):
            return JsonResponse({'code':400,'errmsg':'请输入用户名密码'})
        user = authenticate(request=request,username=username,password=password)
        print(user)
        if not user:
            return JsonResponse({'code':400,'errmsg':'请输入正确的用户名密码'})
        login(request,user)
        if remembered == True :
            request.session.set_expiry(None)
        else:
            request.session.set_expiry(0)

        response =  JsonResponse({'code':0,'errmsg':'登陆成功'})
        response.set_cookie('username',user.username,max_age=3600*24*14)
        return response


class LogoutView(View):
    def delete(self,request):
        logout(request)
        response = JsonResponse({'code':0,'errmsg':'退出成功'})
        response.delete_cookie('username')
        return response

class UserInfoView(LoginRequiredJSONMixin,View):
    def get(self,request):
        # if not request.user.is_authenticated:
        #     return JsonResponse({'code':400,'errmsg':'请登录'})

        return JsonResponse({'code':0,'errmsg':'成功进入','info_data':{'username':request.user.username,'mobile':request.user.mobile,'email':request.user.email,'email_active':request.user.email_active}})






